<?php
namespace App\Services;

use App\Models\WxArea;
use Illuminate\Support\Facades\Cache;

/**
 * 微信地区服务类
 * @package App\Services
 */
class WxAreaService
{
    /**
     * 构造函数
     */
    public function __construct()
    {

    }

    /**
     * 获取地区列表
     * @return array
     */
    public function getAreaList()
    {
        $groupList = WxArea::all();
        return $groupList->toArray();
    }

    /**
     * 获取缓存地区列表
     * @return array|mixed
     */
    public function getCacheAreaList($isRefresh = false)
    {
        $cacheKey = 'wxarea_arealist';
        //Cache::delete($cacheKey);
        $cacheData = Cache::get($cacheKey);
        if (!$cacheData || $isRefresh){
            $cacheData = $this->getAreaList();
            Cache::put($cacheKey, $cacheData, 60);
        }
        return $cacheData;
    }

    /**
     * 获取按父类ID为分组的地区列表
     * @return array
     */
    public function getChunkListByParentId()
    {
        $areaList = $this->getCacheAreaList();
        $chunkList = [];
        if ($areaList){
            foreach ($areaList as $v){
                $parentId = (int) $v['parent_id'];
                isset($chunkList[$parentId]) || $chunkList[$parentId] = [];
                $chunkList[$parentId][] = $v;
            }
        }
        return $chunkList;
    }

    /**
     * 通过地区名称返回地区ID
     * @param $name
     * @return int
     */
    public function getIdByName($name)
    {
        $areaList = $this->getCacheAreaList();
        $arr = array_combine(array_column($areaList, 'id'), array_column($areaList, 'name'));
        $id = array_search($name, $arr);
        return (int) $id;
    }
}